<template>
	<view class="container">
		<!-- Logo区域 -->
		<view class="logo-area">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
			<!-- <text class="app-name">脑卒中预防</text> -->
			<text class="app-name">智能手环</text>
		</view>

		<!-- 角色选择 -->
		<view class="role-selector">
			<view class="role-item" :class="{ active: selectedRole === 'patient' }" @click="selectedRole = 'patient'">
				<text>患者登录</text>
			</view>
			<view class="role-item" :class="{ active: selectedRole === 'doctor' }" @click="selectedRole = 'doctor'">
				<text>医护人员登录</text>
			</view>
		</view>

		<!-- 登录表单 -->
		<view class="login-form">
			<view v-if="loginType === 'account'">
				<view class="input-item">
					<u-icon name="account" size="40" color="#666"></u-icon>
					<input type="text" v-model="form.username" placeholder="请输入手机号/账号" />
				</view>

				<view class="input-item">
					<u-icon name="lock" size="40" color="#666"></u-icon>
					<input type="password" v-model="form.password" placeholder="请输入密码" />
				</view>
			</view>

			<view v-else>
				<view class="input-item">
					<u-icon name="phone" size="40" color="#666"></u-icon>
					<input type="text" v-model="smsForm.phone" placeholder="请输入手机号" maxlength="11" />
				</view>

				<view class="input-item">
					<u-icon name="checkbox-mark" size="40" color="#666"></u-icon>
					<input type="text" v-model="smsForm.code" placeholder="请输入验证码" maxlength="6" />
					<view class="code-btn" @click="getVerifyCode" :class="{ disabled: codeBtnDisabled }">
						<text>{{ codeBtnText }}</text>
					</view>
				</view>
			</view>

			<view class="actions">
				<text @click="goToRegister">注册账号</text>
				<text @click="toggleLoginType">{{ loginType === 'account' ? '短信验证码登录' : '账号密码登录' }}</text>
				<text v-if="loginType === 'account'" @click="goToForget">忘记密码？</text>
			</view>

			<view class="login-btn" @click="handleLogin">
				<text>登 录</text>
			</view>
		</view>

		<!-- 其他登录方式 -->
		<view class="other-login">
			<view class="divider">
				<view class="line"></view>
				<text>其他登录方式</text>
				<view class="line"></view>
			</view>

			<view class="login-methods">
				<view class="method-item" @click="handleOtherLogin('wechat')">
					<u-icon name="weixin-fill" size="64" color="#07c160"></u-icon>
					<text>微信登录</text>
				</view>

				<view class="method-item" @click="handleOtherLogin('qq')">
					<u-icon name="qq-fill" size="64" color="#12B7F5"></u-icon>
					<text>QQ登录</text>
				</view>
			</view>
		</view>

		<!-- 用户协议 -->
		<view class="agreement">
			<checkbox :checked="agreed" @click="agreed = !agreed"></checkbox>
			<text class="text">登录即代表同意</text>
			<text class="link" @click="showAgreement('user')">《用户协议》</text>
			<text class="text">和</text>
			<text class="link" @click="showAgreementP()">《隐私政策》</text>
		</view>
	</view>
</template>

<script>
	import {request,initRequest} from '@/util/request'
	import config from '@/common/config'
	import {
		login,
		sendCode
	} from '@/common/api'

	export default {
		data() {
			return {
				form: {
					username: '111111',
					password: '123456'
				},
				smsForm: {
					phone: '',
					code: ''
				},
				agreed: false,
				selectedRole: 'patient', // 默认选择患者角色
				loginType: 'account', // 默认账号密码登录，可选：account、sms
				codeBtnText: '获取验证码',
				codeBtnDisabled: false,
				timer: null,
				countdown: 60
			}
		},
		methods: {
			goToRegister() {
				uni.navigateTo({
					url: '/pages/login/register'
				})
			},
			goToForget() {
				uni.navigateTo({
					url: '/pages/login/forget'
				})
			},
			toggleLoginType() {
				this.loginType = this.loginType === 'account' ? 'sms' : 'account';
			},
			async getVerifyCode() {
				if (this.codeBtnDisabled) return;

				// 验证手机号
				if (!this.smsForm.phone || !/^1\d{10}$/.test(this.smsForm.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				// 设置按钮禁用状态
				this.codeBtnDisabled = true;
				this.countdown = 60;
				this.codeBtnText = `${this.countdown}秒后重新获取`;

				// 发送验证码请求
				uni.showLoading({
					title: '发送中...'
				});

				try {
					console.log("我在")
					console.log(this.smsForm.phone)
					console.log(this.smsForm)
					// 调用真实的发送验证码接口
					const res = await sendCode({
						params: {
							phonenumber: this.smsForm.phone,
							type: 'login',
						}
					});
					console.log('发送验证码响应:', res);

					uni.hideLoading();

					if (res.code === 200) {
						uni.showToast({
							title: '验证码已发送',
							icon: 'success'
						});

						// 开始倒计时
						this.timer = setInterval(() => {
							this.countdown--;
							this.codeBtnText = `${this.countdown}秒后重新获取`;

							if (this.countdown <= 0) {
								clearInterval(this.timer);
								this.codeBtnText = '获取验证码';
								this.codeBtnDisabled = false;
							}
						}, 1000);
					} else {
						this.codeBtnDisabled = false;
						uni.showToast({
							title: res.msg || '验证码发送失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('发送验证码失败', error);
					uni.hideLoading();
					this.codeBtnDisabled = false;
					uni.showToast({
						title: '验证码发送失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			async handleLogin() {
				if (this.loginType === 'account') {
					if (!this.form.username || !this.form.password) {
						uni.showToast({
							title: '请输入账号和密码',
							icon: 'none'
						})
						return
					}
				} else {
					if (!this.smsForm.phone || !this.smsForm.code) {
						uni.showToast({
							title: '请输入手机号和验证码',
							icon: 'none'
						})
						return
					}
				}

				if (!this.agreed) {
					uni.showToast({
						title: '请先同意用户协议和隐私政策',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '登录中...'
				})

				try {
					let res;

					if (this.loginType === 'account') {
						// 账号密码登录
						
						// res = await request.post('/auth/login', {
						res = await uni.$u.http.post('/auth/login', {
							username: this.form.username,
							password: this.form.password,
							role: this.selectedRole,
							userType: "app_user",
							clientId: config.clientId,
							tenantId: "000000",
							grantType: "password",
							isEncrypt: true,
							repeatSubmit: false
						});
					} else {
						console.log("正在进行短信验证码登录。。。。。。")
						// 短信验证码登录
						res = await login({
							phonenumber: this.smsForm.phone,
							smsCode: this.smsForm.code,
							role: this.selectedRole,
							clientId: config.clientId,
							grantType: "sms",
							tenantId: "000000",
						});
					}

					uni.hideLoading();
					console.log("res")
					console.log(res)
					uni.setStorageSync('token', res.data.access_token);
					console.log(res.data);
					console.log(res.data.access_token);
					const userInfo = {role: this.selectedRole};
					uni.setStorageSync('userInfo', JSON.stringify(userInfo));
                    
					const app = getApp();
					if(app && app.globalData){
						app.globalData.userRole = this.selectedRole;
                    }

					uni.showToast({
						title: '登录成功',
						icon: 'success'
					});

					// 根据角色跳转到不同的首页
					setTimeout(() => {
						if (this.selectedRole === 'doctor') {
							uni.reLaunch({
								url: '/pages/doctor/home'
							});
						} else {
							uni.reLaunch({
								url: '/pages/home/home'
							});
						}
					}, 1500);
					if (app && app.initWebSocket) {
					  // 重新初始化WebSocket连接
					  setTimeout(() => {
						app.initWebSocket();
					  }, 2500); // 延迟500ms确保token已保存
					}
				} catch (error) {
					console.error('登录失败', error);
					uni.hideLoading();
					// uni.showToast({
					// 	title: '登录失败，请稍后重试',
					// 	icon: 'none'
					// });
				}
			},
			handleOtherLogin(type) {
				if (!this.agreed) {
					uni.showToast({
						title: '请先同意用户协议和隐私政策',
						icon: 'none'
					})
					return
				}

				if (type === 'wechat') {
					uni.showToast({
						title: '微信登录功能开发中',
						icon: 'none'
					})
				} else if (type === 'qq') {
					uni.showToast({
						title: 'QQ登录功能开发中',
						icon: 'none'
					})
				}
			},
			showAgreement(type) {
				uni.navigateTo({
					url: '/pages/login/protocol'
				})
			},
			showAgreementP() {
				uni.navigateTo({
					url: '/pages/login/agreement'
				})
			}
		},
		onUnload() {
			// 清除定时器
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		}
	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #fff;
		padding: 60rpx 40rpx;

		.logo-area {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 40rpx;

			.logo {
				width: 160rpx;
				height: 160rpx;
				margin-bottom: 30rpx;
			}

			.app-name {
				font-size: 40rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.role-selector {
			display: flex;
			margin-bottom: 40rpx;
			border-radius: 12rpx;
			overflow: hidden;
			background-color: #f5f5f5;

			.role-item {
				flex: 1;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					font-size: 28rpx;
					color: #666;
				}

				&.active {
					background-color: #1890FF;

					text {
						color: #fff;
						font-weight: bold;
					}
				}
			}
		}

		.login-form {
			.input-item {
				display: flex;
				align-items: center;
				height: 100rpx;
				background-color: #F7F7FA;
				border-radius: 50rpx;
				padding: 0 40rpx;
				margin-bottom: 30rpx;

				input {
					flex: 1;
					height: 100%;
					font-size: 28rpx;
					color: #333;
					margin-left: 20rpx;
				}

				.code-btn {
					padding: 0 30rpx;
					height: 60rpx;
					background-color: #1890FF;
					border-radius: 30rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					text {
						font-size: 24rpx;
						color: #fff;
					}

					&.disabled {
						background-color: #ccc;
					}
				}
			}

			.actions {
				display: flex;
				justify-content: space-between;
				margin-bottom: 60rpx;

				text {
					font-size: 28rpx;
					color: #666;
				}
			}

			.login-btn {
				height: 88rpx;
				background-color: #1890FF;
				border-radius: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					font-size: 32rpx;
					color: #fff;
					font-weight: bold;
				}
			}
		}

		.other-login {
			margin-top: 80rpx;

			.divider {
				display: flex;
				align-items: center;
				margin-bottom: 60rpx;

				.line {
					flex: 1;
					height: 2rpx;
					background-color: #EEEEEE;
				}

				text {
					font-size: 24rpx;
					color: #999;
					padding: 0 30rpx;
				}
			}

			.login-methods {
				display: flex;
				justify-content: space-around;

				.method-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					margin: 0 40rpx;

					text {
						font-size: 24rpx;
						color: #666;
						margin-top: 20rpx;
					}
				}
			}
		}

		.agreement {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 60rpx;

			checkbox {
				transform: scale(0.8);
				margin-right: 5rpx;
			}

			.text {
				font-size: 24rpx;
				color: #666;
			}

			.link {
				font-size: 24rpx;
				color: #1890FF;
			}
		}
	}
</style>